<template>
  <div class="process-flow-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>工艺流程管理</h2>
      <p>管理工艺流程信息，查看工艺流程步骤详情</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="流程编号/名称">
            <el-input
              v-model="searchForm.NumberOrName"
              placeholder="请输入流程编号或名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="负责人">
            <el-input
              v-model="searchForm.ResponsiblePerson"
              placeholder="请输入负责人"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-input
              v-model="searchForm.Department"
              placeholder="请输入部门"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.IsActive"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 工艺流程列表 -->
    <div class="table-section">
      <el-card>
        <div class="table-header">
          <h3>工艺流程列表</h3>
          <div class="header-actions" v-if="selectedRows.length > 0">
            <el-button type="danger" size="small" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>
              批量删除 ({{ selectedRows.length }})
            </el-button>
            <el-button type="info" size="small" @click="handleClearSelection">
              <el-icon><Close /></el-icon>
              取消选择
            </el-button>
          </div>
        </div>
        
        <el-table
          ref="tableRef"
          :data="processFlowList"
          v-loading="loading"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <!-- 多选列 -->
          <el-table-column type="selection" width="55" align="center" />
          
          <!-- 序号列 -->
          <el-table-column label="序号" width="80" align="center">
            <template #default="{ $index }">
              {{ (pagination.pageIndex - 1) * pagination.pageSize + $index + 1 }}
            </template>
          </el-table-column>
          
          <el-table-column prop="processFlowNumber" label="流程编号" width="120" />
          <el-table-column prop="processFlowName" label="流程名称" min-width="200" />
          <el-table-column prop="processCount" label="工序数量" width="100" align="center" />
          <el-table-column prop="responsiblePerson" label="负责人" width="120" />
          <el-table-column prop="department" label="所属部门" width="120" />
          <el-table-column prop="isActive" label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isActive ? 'success' : 'danger'">
                {{ row.isActive ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewDetails(row)">
                详情
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 工艺流程详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      :title="`工艺流程详情 - ${detailDialog.data?.processFlowName || ''}`"
      width="90%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <div v-if="detailDialog.data" class="detail-content">
        <!-- 基本信息 -->
        <el-card class="detail-card">
          <template #header>
            <div class="detail-card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="流程编号">
              {{ detailDialog.data.processFlowNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="流程名称">
              {{ detailDialog.data.processFlowName }}
            </el-descriptions-item>
            <el-descriptions-item label="工序数量">
              {{ detailDialog.data.processCount }}
            </el-descriptions-item>
            <el-descriptions-item label="负责人">
              {{ detailDialog.data.responsiblePerson || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="所属部门">
              {{ detailDialog.data.department || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="detailDialog.data.isActive ? 'success' : 'danger'">
                {{ detailDialog.data.isActive ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="3">
              {{ detailDialog.data.remarks || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(detailDialog.data.createdTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDate(detailDialog.data.updatedTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 工序步骤信息 -->
        <el-card class="detail-card">
          <template #header>
            <div class="detail-card-header">
              <span>工序步骤</span>
              <el-button 
                type="success" 
                size="small" 
                @click="handleExportSteps"
                :loading="exportLoading"
                :disabled="!processSteps || processSteps.length === 0"
              >
                <el-icon><Download /></el-icon>
                导出Excel
              </el-button>
            </div>
          </template>
          
          <el-table
            :data="processSteps"
            v-loading="stepsLoading"
            stripe
            style="width: 100%"
          >
            <el-table-column prop="stepOrder" label="序号" width="80" align="center" />
            <el-table-column prop="processNumber" label="工序编号" width="120" />
            <el-table-column prop="processName" label="工序名称" min-width="150" />
            <el-table-column prop="processCategoryName" label="工序分类" width="120" />
            <el-table-column prop="responsiblePerson" label="负责人" width="120" />
            <el-table-column prop="department" label="所属部门" width="120" />
            <el-table-column prop="stepRemarks" label="步骤备注" min-width="150">
              <template #default="{ row }">
                <span>{{ row.stepRemarks || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="processRemarks" label="工序备注" min-width="150">
              <template #default="{ row }">
                <span>{{ row.processRemarks || '-' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handlePrintFromDialog">
            <el-icon><Printer /></el-icon>
            打印详情
          </el-button>
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Printer, Download, Delete, Close } from '@element-plus/icons-vue'
import {
  getProcessFlowPage,
  getProcessFlowById,
  getProcessFlowSteps,
  deleteProcessFlow,
  batchDeleteProcessFlows,
  printProcessFlowDetailsToPdf,
  exportProcessFlowStepsToExcel
} from '@/services/ProcessManagementApi'
import type { ProcessFlow, ProcessFlowStep, ProcessFlowQueryParams } from '@/types/process'

// 搜索表单
const searchForm = reactive<ProcessFlowQueryParams>({
  NumberOrName: '',
  ResponsiblePerson: '',
  Department: '',
  IsActive: undefined
})

// 分页信息
const pagination = reactive({
  pageIndex: 1,
  pageSize: 20,
  total: 0
})

// 工艺流程列表
const processFlowList = ref<ProcessFlow[]>([])
const loading = ref(false)

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null as ProcessFlow | null
})

// 工序步骤
const processSteps = ref<ProcessFlowStep[]>([])
const stepsLoading = ref(false)
// 导出加载状态
const exportLoading = ref(false)

// 批量删除选中项
const selectedRows = ref<ProcessFlow[]>([])
const tableRef = ref<any>(null)


// 获取工艺流程列表
const fetchProcessFlows = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize
    }
    
    const result = await getProcessFlowPage(params)
    
    if (result.code === 200) {
      processFlowList.value = result.pageData || []
      pagination.total = result.totaCount || 0
    } else {
      ElMessage.error(result.msg || '获取工艺流程列表失败')
    }
  } catch (error) {
    console.error('获取工艺流程列表失败:', error)
    ElMessage.error('获取工艺流程列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchProcessFlows()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    NumberOrName: '',
    ResponsiblePerson: '',
    Department: '',
    IsActive: undefined
  })
  pagination.pageIndex = 1
  fetchProcessFlows()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchProcessFlows()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchProcessFlows()
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的工艺流程')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个工艺流程吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

         const ids = selectedRows.value.map(item => item.id)
     const result = await batchDeleteProcessFlows(ids)

    if (result.code === 200) {
      ElMessage.success('批量删除成功')
      // 重新加载数据
      await fetchProcessFlows()
      // 清空选中项
      selectedRows.value = []
    } else {
      ElMessage.error(result.msg || '批量删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请重试')
    }
  }
}

// 取消选择
const handleClearSelection = () => {
  tableRef.value.clearSelection()
  selectedRows.value = []
}

// 选择变化
const handleSelectionChange = (selection: ProcessFlow[]) => {
  selectedRows.value = selection
}

// 查看详情
const viewDetails = async (row: ProcessFlow) => {
  try {
    // 获取详细信息
    const result = await getProcessFlowById(row.id)
    if (result.code === 200) {
      detailDialog.data = result.data
      detailDialog.visible = true
      
      // 获取工序步骤
      await fetchProcessSteps(row.id)
    } else {
      ElMessage.error(result.msg || '获取工艺流程详情失败')
    }
  } catch (error) {
    console.error('获取工艺流程详情失败:', error)
    ElMessage.error('获取工艺流程详情失败')
  }
}

// 获取工序步骤
const fetchProcessSteps = async (processFlowId: number) => {
  stepsLoading.value = true
  try {
    const result = await getProcessFlowSteps(processFlowId)
    if (result.code === 200) {
      processSteps.value = result.data || []
    } else {
      ElMessage.error(result.msg || '获取工序步骤失败')
    }
  } catch (error) {
    console.error('获取工序步骤失败:', error)
    ElMessage.error('获取工序步骤失败')
  } finally {
    stepsLoading.value = false
  }
}

// 编辑工艺流程
const handleEdit = (row: ProcessFlow) => {
  ElMessage.info(`编辑工艺流程: ${row.processFlowName}`)
  // TODO: 实现编辑功能，可以打开编辑对话框
  console.log('编辑工艺流程:', row)
}

// 删除工艺流程
const handleDelete = async (row: ProcessFlow) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工艺流程"${row.processFlowName}"吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用删除API
    const result = await deleteProcessFlow(row.id)
    if (result.code === 200) {
      ElMessage.success('删除成功')
      // 重新加载数据
      await fetchProcessFlows()
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除工艺流程失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 打印工艺流程详情
const handlePrint = async (row: ProcessFlow) => {
  try {
    ElMessage.info('正在生成PDF文件，请稍候...')
    await printProcessFlowDetailsToPdf(row.id)
    ElMessage.success('打印文件已生成并下载')
  } catch (error: any) {
    console.error('打印工艺流程详情失败:', error)
    ElMessage.error(error.message || '打印失败，请重试')
  }
}

// 打印详情按钮点击
const handlePrintFromDialog = async () => {
  if (detailDialog.data) {
    try {
      ElMessage.info('正在生成PDF文件，请稍候...')
      await printProcessFlowDetailsToPdf(detailDialog.data.id)
      ElMessage.success('打印文件已生成并下载')
    } catch (error: any) {
      console.error('打印工艺流程详情失败:', error)
      ElMessage.error(error.message || '打印失败，请重试')
    }
  }
}

// 导出工序步骤到Excel
const handleExportSteps = async () => {
  if (!detailDialog.data) {
    ElMessage.error('未选择工艺流程')
    return
  }

  exportLoading.value = true
  try {
    ElMessage.info('正在生成Excel文件，请稍候...')
    await exportProcessFlowStepsToExcel(detailDialog.data.id)
    ElMessage.success('Excel文件已生成并下载')
  } catch (error: any) {
    console.error('导出工序步骤失败:', error)
    ElMessage.error(error.message || '导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 格式化日期
const formatDate = (date?: string | Date) => {
  if (!date) return '-'
  const d = new Date(date)
  if (isNaN(d.getTime())) return '-'
  return d.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化
onMounted(() => {
  fetchProcessFlows()
})
</script>

<style scoped>
.process-flow-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-content {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.detail-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #303133;
  font-weight: 600;
}
</style> 